#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main()
{
    int ret = 0;
    int fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[BUFFER_SIZE];

    // 创建socket文件描述符
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 绑定socket到端口
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);
    ret = bind(fd, (struct sockaddr*)&address, sizeof(address));
    if (ret < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 等待客户端发送客户端地址信息过来，拿到地址信息后，服务端就不断的向该客户端推送数据
    while (true) {
        // udp 在接受消息的时候，除了消息本身外，还会接受到发送者的地址信息
        ret = recvfrom(fd, (char*)buffer, BUFFER_SIZE, MSG_WAITALL, (struct sockaddr*)&address, (socklen_t*)&addrlen);
        if (ret < 0) {
            perror("recvfrom");
            exit(EXIT_FAILURE);
        }

        // 判断 buffer 的内容 + 线程的状态
        // buffer = connect
        // buffer = disconnect

        buffer[ret] = '\0';
        std::cout << "Received: " << buffer << std::endl;

        if (strcmp(buffer, "connect") == 0) {
            std::cout << "connect" << std::endl;
            // 创建线程

        } else if (strcmp(buffer, "disconnect") == 0) {
            std::cout << "disconnect" << std::endl;

            // 销毁线程
        }

        // 关闭线程

        // 发送数据回客户端
        ret = sendto(fd, (const char*)buffer, strlen(buffer), MSG_CONFIRM, (const struct sockaddr*)&address, addrlen);
        if (ret < 0) {
            perror("sendto");
            exit(EXIT_FAILURE);
        }

        usleep(100 * 1000);
    }

    return 0;
}
